//! 字符串加密库

use super::*;

/// 字符串加密
#[allow(dead_code)]
#[wasm_bindgen]
pub fn encrypt(value: String) -> String {
    let key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let key_len = key.len();
    let key_str: Vec<char> = key.to_string().chars().collect();
    let mut list: Vec<char> = Vec::new();

    let mut b;
    let mut b1;
    let mut b2;
    let mut b3;
    for c in value.chars() {
        b = c as i32; //逐个提取每个字符，并获取Unicode编码值
        b1 = b % key_len as i32; //求Unicode编码值得余数
        b = (b - b1) / key_len as i32; //求最大倍数
        b2 = b % key_len as i32; //求最大倍数的于是
        b = (b - b2) / key_len as i32; //求最大倍数
        b3 = b % key_len as i32; //求最大倍数的余数
        let k_b3 = key_str[b3 as usize];
        let k_b2 = key_str[b2 as usize];
        let k_b1 = key_str[b1 as usize];
        list.push(k_b3);
        list.push(k_b2);
        list.push(k_b1);
    }
    let a: String = list.iter().collect();
    a
}

/// 编码解码
#[allow(dead_code)]
#[wasm_bindgen]
pub fn decrypt(value: String) -> String {
    let key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let key_len = key.len();
    let mut b1: usize;
    let mut b2: usize;
    let mut b3: usize;
    let mut d = 0;
    let val_len = value.len() / 3;
    let value_str: Vec<_> = value.split("").collect();

    if value_str.len() <= 0 {
        return "".to_string();
    }
    let value_str = value_str.get(1..value_str.len() - 1).unwrap();
    let mut decrypt_str: Vec<char> = Vec::new();

    for _ in 0..val_len {
        b1 = key.find(value_str[d]).unwrap();
        d = d + 1;
        b2 = key.find(value_str[d]).unwrap();
        d = d + 1;
        b3 = key.find(value_str[d]).unwrap();
        d = d + 1;
        let code = b1 * key_len * key_len + b2 * key_len + b3;
        match char::from_u32(code as u32) {
            Some(value) => decrypt_str.push(value),
            None => {}
        }
    }
    let value: String = decrypt_str.iter().collect();
    value
}
